package com.zsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.context.BaseContext;
import com.zsc.entity.AddressBook;
import com.zsc.mapper.AddressBookMapper;
import com.zsc.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author cjr165123050
 * @description 针对表【address_book(地址簿)】的数据库操作Service实现
 * @createDate 2024-05-19 11:14:19
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询当前用户地址信息
     *
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        QueryWrapper<AddressBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", addressBook.getUserId());

        // queryWrapper.eq("phone", addressBook.getPhone());
        if (addressBook.getIsDefault() != null) {
            queryWrapper.eq("is_default", addressBook.getIsDefault());
        }
        return addressBookMapper.selectList(queryWrapper);
    }


    /**
     * 新增地址簿信息
     *
     * @param addressBook
     * @return
     */
    @Override
    public boolean save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        return super.save(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();

        // 使用UpdateWrapper将当前用户的所有地址修改为非默认地址
        UpdateWrapper<AddressBook> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId).set("is_default", 0);
        this.update(updateWrapper);

        // 将当前地址改为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);
    }
}




